'''
File:           gcalendar.py
Date:           1/17/2011
Description:    This code provides an interface to the google calendar API for use with the eventmanager
Dependencies:   gdata
Changelog:
                11/17/2011    MRB    Initial Version
'''
try:
  from xml.etree import ElementTree # for Python 2.5 users
except ImportError:
  from elementtree import ElementTree
import gdata.calendar.service
import gdata.service
import atom.service
import gdata.calendar
import atom
import getopt
import sys
import string
import time
from datetime import timedelta

from django.conf import settings
from ocms.eventmanager.models import *

class GoogleCalendarWrapper():
    
    _calendar_service = gdata.calendar.service.CalendarService()
    _calendar = settings.EVENT_CALENDAR
    
    def __init__(self):
        self._calendar_service.email = settings.EMAIL_HOST_USER
        self._calendar_service.password = settings.EMAIL_HOST_PASSWORD
        self._calendar_service.source = 'Google-Calendar_Python_Sample-1.0'
        self._calendar_service.ProgrammaticLogin()
        self._calendar = settings.EVENT_CALENDAR

    def AddEvent(self, eEvent):
        title=eEvent.Name 
        content=eEvent.TxtContent()
        where=eEvent.Location
        start_time=eEvent.Start_Date.strftime('%Y-%m-%d')
        end_time=(eEvent.End_Date + datetime.timedelta(days=1)).strftime('%Y-%m-%d') #gcal will show this improperly unless we add a day
    
        event = gdata.calendar.CalendarEventEntry()
        event.title = atom.Title(text=title)
        event.content = atom.Content(text=content)
        event.where.append(gdata.calendar.Where(value_string=where))
        event.when.append(gdata.calendar.When(start_time=start_time, end_time=end_time))
        
        new_event = self._calendar_service.InsertEvent(event, '/calendar/feeds/'+str(self._calendar)+'/private/full')
    
        #get event id with new_event.id.text
        return new_event    
    
    def UpdateEvent(self, eEvent):
      event = self.GetEvent(str(eEvent.gcal_id))
      
      event.title.text = eEvent.Name
      event.content.text=eEvent.TxtContent()
      event.where=gdata.calendar.Where(value_string=eEvent.Location)
      event.when=gdata.calendar.When(start_time=eEvent.Start_Date.strftime('%Y-%m-%d'), end_time=(eEvent.End_Date + datetime.timedelta(days=1)).strftime('%Y-%m-%d')) 
      
      return self._calendar_service.UpdateEvent(event.GetEditLink().href, event)
    
    def GetEvent(self, event_id):
        return self._calendar_service.GetCalendarEventEntry(event_id)
    